package com.dm.shop.common.exception;

import com.dm.shop.utils.ResultUtil;
import com.dm.shop.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;


/**
 * @author jingjiao wang
 * @version 1.0
 * @date 2021/7/21 21:22
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 统一处理某一类异常，从而能够减少代码重复率和复杂度
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result commonExceptionHandler(Exception e){
        log.error(e.toString());
        if(e instanceof SystemException){
            SystemException systemException=(SystemException)e;
            return ResultUtil.error(systemException.getMsg());

        }else {
            return ResultUtil.error(e.getMessage());
        }
    }
    //DTO参数校验的异常处理
    @ResponseBody
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result argumentExceptionHandle(MethodArgumentNotValidException e){
        log.error(e.toString());  // 记录错误信息
        /**
         * BindingResult用在实体类校验信息返回结果绑定。
         *https://blog.csdn.net/soulofball/article/details/112011877
         */
        List<ObjectError> errorList=e.getBindingResult().getAllErrors();
        String error="参数错误";
        for (ObjectError objectError : errorList) {
            error=objectError.getDefaultMessage();
        }
        return ResultUtil.error(error);
    }
}
